import os, requests, hashlib, tarfile
# web1_ver_path: web1服务器存储部署项目版本号的文件路径
# ver_url: jenkins服务器存储版本号的url地址
def has_new_version(web1_ver_path, ver_url):
    if os.path.exists(web1_ver_path) == False:
        return True  # 需要下载
    # 本地文件版本号与jenkins服务器存储的版本号对比
    with open(web1_ver_path, mode="r") as fr:
        local_ver = fr.read()
    resp = requests.get(ver_url)
    if local_ver != resp.text:
        return True  # 版本号不等，需要下载
    return False # 版本号相等，不需要下载

def file_ok(web1_tar_path, jenkins_tar_md5_url):
    m = hashlib.md5()
    with open(web1_tar_path, mode="rb") as fr:
        while True:
            data = fr.read(4096)  # 4k
            if len(data) == 0:
                break
            m.update(data)  # 批量计算文件md5值
    resp = requests.get(jenkins_tar_md5_url)
    if m.hexdigest() == resp.text.strip():
        print("没有丢包")
        return True  # 没有丢包，返回True
    return False  # 丢包，返回False

def deploy(web1_tar_path, web1_deploy_dir, dest):
    tar = tarfile.open(web1_tar_path)
    tar.extractall(path=web1_deploy_dir)# 解压到指定的位置
    tar.close()
    fname=os.path.basename(web1_tar_path)#myproject-1.1.tar.gz
    fname = fname[:-7]  # myproject-1.1
    app_dir = os.path.join(web1_deploy_dir,fname)
    # 目标app_dir：/var/www/deploy/myproject-1.1
    if os.path.exists(dest):
        os.remove(dest)  # 软链接存在则删除
    os.symlink(app_dir, dest)  # 创建软链接指向目标目录



if __name__ == "__main__":
    web1_ver_path = "/var/www/deploy/ver.txt"
    ver_url = "http://192.168.88.30/deploy/ver.txt"
    if has_new_version(web1_ver_path, ver_url) == False:
        print("没有新版本~")
        exit()
    # 如果有新版本，下载新版本
    resp = requests.get(ver_url)
    jenkins_tar_url = f"http://192.168.88.30/deploy/packages/myproject-{resp.text}.tar.gz"
    web1_tar_path = f"/var/www/download/myproject-{resp.text}.tar.gz"
    with open(web1_tar_path, mode="wb") as fw:
        fw.write(requests.get(jenkins_tar_url).content)
        print("web1服务器下载完毕")
    # 校验文件的完整性
    jenkins_tar_md5_url = jenkins_tar_url + ".md5"
    # 调用函数
    if file_ok(web1_tar_path, jenkins_tar_md5_url)==False:
        print("丢包了")
        os.remove(web1_tar_path)
        exit()
    web1_deploy_dir = "/var/www/deploy"  # 部署路径
    dest = "/var/www/html/current"  # 暴露接口的软链接
    # web1: http://192.168.88.100/current
    deploy(web1_tar_path, web1_deploy_dir, dest)
    # 更新本地的版本文件
    if os.path.exists(web1_ver_path):
        os.remove(web1_ver_path)
    with open(web1_ver_path, mode="w") as fw:
        fw.write(requests.get(ver_url).text)  # 写入新版本号